package com.lalilu.lread.ui.weight

import android.content.Context
import android.graphics.PointF
import android.util.AttributeSet
import android.view.MotionEvent
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import kotlin.math.abs

/**
 *  重新SmartRefreshLayout的滑动事件分发逻辑，
 *  竖向滑动开始后屏蔽父级的横向滑动
 */
class MyRefreshLayout(context: Context?, attrs: AttributeSet?) :
    SmartRefreshLayout(context, attrs) {

    // 存储点击点的位置信息
    private val mPointGapF: PointF = PointF(0f, 0f)
    private var isSolve: Boolean = false
    private var isIntercept: Boolean = false

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {

        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mPointGapF.set(ev.x, ev.y)
                parent.requestDisallowInterceptTouchEvent(true)
            }
            MotionEvent.ACTION_MOVE -> {
                if (!isSolve) {
                    val disX = abs(ev.x - mPointGapF.x)
                    val disY = abs(ev.y - mPointGapF.y)
                    if (disX != disY) {
                        // 判断滑动的方向，如果是竖向滑动则触发拦截
                        isIntercept = disX < disY
                        isSolve = true
                    }
                }
                parent.requestDisallowInterceptTouchEvent(isIntercept)
            }
            MotionEvent.ACTION_CANCEL,
            MotionEvent.ACTION_UP -> {
                isIntercept = false
                isSolve = false
                parent.requestDisallowInterceptTouchEvent(false)
            }
        }
        return super.dispatchTouchEvent(ev)
    }
}